package cn.xjt.Unsafe;

/**
 * 不安全的线程案例
 * 不安全的银行
 * @author xujiangtao
 * @create 2020-08-01-13:18
 */
public class UnfaseBankThread {
    public static void main(String[] args) {
        Account a = new Account(1000,"结婚基金");
        drawMoney you = new drawMoney(a,50,"你");
        drawMoney grilfriend = new drawMoney(a,100,"女朋友");
        you.start();
        grilfriend.start();
    }
}
//银行账户
class Account{
     int money;
     String name;
    public Account(int money,String name)
    {
        this.money=money;
        this.name=name;
    }
}
class drawMoney extends Thread{
    Account account;
    int drawmoney;
    int nowMoney;
    public drawMoney(Account account,int drawmoney,String name)
    {
        super(name);
        this.account=account;
        this.drawmoney=drawmoney;
    }
    //synchronized默认锁得是this.
    //锁的对象应该是变化的量
    @Override
    public void run() {
        synchronized(account)   //这里是锁的方法块，如果线程访问就会被锁住
        {
            if(account.money<drawmoney)
            {
                System.out.println(Thread.currentThread().getName()+"的账户余额不足\t"+drawmoney);
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额=账户金额-取款金额
            account.money=account.money-drawmoney;
            //你手里的钱
            nowMoney=nowMoney+drawmoney;
            //账户余额
            System.out.println(account.name+"余额为:"+account.money);
            //你手里的钱
            System.out.println(this.getName()+"余额为:"+nowMoney);
        }

    }
}

